package formal.tree.bst;

import java.util.ArrayList;

/**
 * @author DengYuan2
 * @create 2021-01-10 13:29
 */

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                '}';
    }

    /**
     *                      1
     *        2                         2
     *   3         null           null        3
     *4    null                           null  4
     * @param
     * @return
     */
    public static TreeNode generateTree(Integer[] a) {
        if (a==null){
            return null;
        }
        ArrayList<TreeNode> list = new ArrayList<>(a.length);
        for (int i = 0; i < a.length; i++) {
            if (a[i]!=null){
                TreeNode treeNode = new TreeNode(a[i]);
                list.add(treeNode);
            }else {
                list.add(null);
            }
        }
        TreeNode parent = null;
        TreeNode left = null;
        TreeNode right = null;
        int j = 0;
        for (int i = 0; i < list.size()&&j<list.size()-1; i++) {
            if (list.get(i)==null){
                continue;
            }
            parent=list.get(i);
            left=list.get(++j);
            right = list.get(++j);
            parent.left=left;
            parent.right = right;
        }

        return list.get(0);
    }

//    public static void main(String[] args) {
//
//        TreeNode treeNode = TreeNode.generateTree(null);
//        System.out.println(treeNode);
//
//    }

    public void pre(TreeNode root){
        if (root==null){
            return;
        }
        System.out.println(root.val);
        pre(root.left);
        pre(root.right);
    }
}